package com.example.dormitorysystem.common.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.example.dormitorysystem.common.jwt.JwtUtil;
import com.example.dormitorysystem.entity.Logs;
import com.example.dormitorysystem.mapper.LogsMapper;
import com.example.dormitorysystem.utils.IPUtils;
import com.example.dormitorysystem.utils.Response;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chen huilong
 * @data 2022/11/27
 * 操作日志切面处理类
 */
@Aspect
@Component
public class OperationLogAspect {

    private final String UserLogin = "UserLogin";

    @Resource
    LogsMapper logsMapper;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 设置操作日志切入点   在注解的位置切入代码
     */
    @Pointcut("@annotation(com.example.dormitorysystem.common.aop.OperationLogAnnotation)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.example.dormitorysystem.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 记录操作日志
     *
     * @param joinPoint 方法的执行点
     * @param result    方法返回值
     * @throws Throwable
     */
    @AfterReturning(returning = "result", value = "operLogPoinCut()")
    public void saveOperLog(JoinPoint joinPoint, Object result) throws Throwable {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Logs operationLog = new Logs();
        try {

            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
            if (annotation != null) {
                operationLog.setOperation(annotation.operModul());
                operationLog.setOperType(annotation.operType());
                operationLog.setOperDesc(annotation.operDesc());
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            operationLog.setMethod(methodName);

            Object[] parameterValues = joinPoint.getArgs();
            try {
                Map<String, Object> requestBody = (Map<String, Object>) parameterValues[0];
                // 将参数所在的数组转换成json
                String params = JSON.toJSONString(requestBody);
                operationLog.setRequestBody(params);
            } catch (Exception e) {
                // 请求的参数
                Map<String, String> rtnMap = converMap(request.getParameterMap());
                // 将参数所在的数组转换成json
                String params = JSON.toJSONString(rtnMap);
                operationLog.setRequestBody(params);
            }

            // 返回结果
            operationLog.setResponseBody(JSON.toJSONString(result));
            // 操作时间
            operationLog.setCreateTime(Timestamp.valueOf(sdf.format(new Date())));
            // 操作用户
            //String token = request.getHeader("token");
            //Map<String, Claim> userData = JwtUtil.verifyToken(token);
            //Integer uid = Integer.parseInt(userData.get("uid").asString());
            //operationLog.setUid(uid);
            operationLog.setUid(1);
            // 操作IP
            operationLog.setClientIp(IPUtils.getIpAddr(request));
            // 请求URI
            operationLog.setRequestUri(request.getRequestURI());
            // 状态
            operationLog.setStatus(0);

            // 保存日志
            logsMapper.insert(operationLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        Logs operationLog = new Logs();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
            if (annotation != null) {
                operationLog.setOperation(annotation.operModul());
                operationLog.setOperType(annotation.operType());
                operationLog.setOperDesc(annotation.operDesc());
            }


            Object[] parameterValues = joinPoint.getArgs();
            try {
                Map<String, Object> requestBody = (Map<String, Object>) parameterValues[0];
                // 将参数所在的数组转换成json
                String params = JSON.toJSONString(requestBody);
                operationLog.setRequestBody(params);
            } catch (Exception exception) {
                // 请求的参数
                Map<String, String> rtnMap = converMap(request.getParameterMap());
                // 将参数所在的数组转换成json
                String params = JSON.toJSONString(rtnMap);
                operationLog.setRequestBody(params);
            }

            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            operationLog.setMethod(methodName);

            // 异常信息
            operationLog.setResponseBody(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));

            // 操作用户
            if (UserLogin.equals(annotation.operType())) {

            } else {

            }
            //String token = request.getHeader("token");
            //Map<String, Claim> userData = JwtUtil.verifyToken(token);
            //Integer uid = Integer.parseInt(userData.get("uid").asString());
            //operationLog.setUid(uid);
            operationLog.setUid(1);

            operationLog.setRequestUri(request.getRequestURI());
            operationLog.setClientIp(IPUtils.getIpAddr(request));

            // 发生异常时间
            operationLog.setCreateTime(new Date());

            // 设置状态：失败
            operationLog.setStatus(1);

            logsMapper.insert(operationLog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "n");
        }
        String message = exceptionName + ":" + exceptionMessage + "nt" + strbuff.toString();
        return message;
    }


}
